<%--
  Created by IntelliJ IDEA.
  User: King
  Date: 2020/9/28
  Time: 13:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>展示成绩</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/bootstrap.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/pintuer.css">
</head>
<body>
<div class="row margin">
    <div class="col-lg-2"><button type="button" class="btn btn-primary  btn-sm" onclick="showStuById(0)">增加学生</button></div>
    <div class="col-lg-6">
        <div class="input-group">
            <input type="text" id="searchInput" class="form-control" placeholder="Search for...">
            <span class="input-group-btn">
        <button onclick="searchUesr(1)" class="btn btn-default" type="button">搜索</button>
      </span>
        </div>
    </div>
</div>

<div class="row margin">
    <table class="table">
        <thead>
        <tr>
            <td>编号</td>
            <td>姓名</td>
            <td>学科</td>
            <td>成绩</td>
        </tr>
        </thead>
        <tbody id="tb">

        </tbody>
    </table>
</div>
<div class="margin">
    每页显示<select id="pageSizeSelect">
    <option value="2" selected="selected">2</option>
    <option value="5">5</option>
    <option value="10">10</option>
</select>条数据，当前是第<span id="currentPageSpan">1</span>页，
    总共<span id="totalPageSpan"></span> 页
    <button id="firstPageButton" class="button" onclick="firstPage()">首页</button>
    <button id="prePageButton" class="button" onclick="prePage()">上一页</button>
    <button id="nextPageButton" class="button" onclick="nextPage()">下一页</button>
    <button id="lastPageButton" class="button" onclick="lastPage()">尾页</button>
</div>


<div class="modal" id="editModal">
    <!-- 对话模态框-->
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4>学生信息编辑</h4>
            </div>
            <div class="modal-body">
                <label class="control-label">用户姓名</label>
                <input class="form-control" type="text" id="nameInput" placeholder="请输入用户姓名">
                <label class="control-label">性别</label>
                <select id="sexSelect" class="form-control">
                    <option value="0">男</option>
                    <option value="1">女</option> </select>
                <label class="control-label">地址</label>
                <input class="form-control" type="text" id="addressInput" placeholder="请输入地址">
                <label class="control-label">出生年月</label>
                <input class="form-control" type="text" id="birthdayInput" placeholder="请输入出生年月">
                <label class="control-label">班级</label>
                <select id="classSelect" class="form-control">
                </select>
                <input type="hidden" id="stuIdInput">
            </div>
            <div class="modal-footer">
                <button class="button" data-dismiss="modal">取消</button>
                <button class="button" onclick="editConfirm()">确定</button>
            </div>
        </div>
    </div>
</div>
<script src="${pageContext.request.contextPath}/static/jquery-3.2.1.min.js"></script>
<script src="${pageContext.request.contextPath}/static/js/bootstrap.min.js"></script>
<script>
    /*页面加载好后获取用户数据*/
    $(function(){
        LoadUserList();
    });

    var search;

    /*上一页*/
    function prePage(){
        let currentPage = $("#currentPageSpan").html();
        currentPage = parseInt(currentPage) - 1;
        $("#currentPageSpan").html(currentPage);
        if(search != null && search != ''){
            console.log(search);
            searchUesr(currentPage);
        }else {
            LoadUserList();
        }
    }

    /*下一页*/
    function nextPage(){
        var currentPage = $("#currentPageSpan").html();
        currentPage = parseInt(currentPage) + 1;
        $("#currentPageSpan").html(currentPage);
        if(search != null && search != ''){
            /* console.log(search);*/
            searchUesr(currentPage);
        }else {
            LoadUserList();
        }
    }

    /*首页*/
    function firstPage(){
        $("#currentPageSpan").html('1');
        if(search != null && search != ''){
            searchUesr(1);
        }else {
            LoadUserList();
        }
        $("#firstPageButton").attr("disabled",true);
        $("#lastPageButton").attr("disabled",false);
    }

    /*尾页*/
    function lastPage(){
        var totalPage = $("#totalPageSpan").html();
        $("#currentPageSpan").html(totalPage);
        if(search != null && search != ''){
            searchUesr(totalPage);
        }else {
            LoadUserList();
        }
        $("#firstPageButton").attr("disabled",false);
        $("#lastPageButton").attr("disabled",true);
    }

    /*改变每页用户数据条数*/
    $("#pageSizeSelect").change(function(){
        $("#currentPageSpan").html('1');
        LoadUserList();
    });

    /*展示查询出来的用户信息*/
    function showUserList(stuList) {
        //console.log(JSON.stringify(userList));
        /*创建一个变量存放添加到页面中的用户信息*/
        var html = '';
        //遍历userList数组
        for(var i=0; i<stuList.length; i++){
            //创建一个变量存放每一个用户信息
            var item = stuList[i];
            //console.log(JSON.stringify(item))
            html+="<tr>";
            html+="<td>" + item.id +"</td>"; //显示用户的id
            html+="<td>" + item.name.replace(search,'<font color="#FF0000" size="4px">'+search+'</font>') +"</td>"; //显示用户的姓名
            if(item.sex == 1){
                html+="<td>女</td>";
            }else{
                html+="<td>男</td>";
            }
            html+="<td>" + item.address.replace(search,'<font color="#FF0000" size="4px">'+search+'</font>') +"</td>"; //显示用户的地址
            html+="<td>" + getLocalTime(new Date(item.birthday)) +"</td>";
            html+="<td>" + item.classes.name +"</td>";
            html+="<td><button class='button' onclick='showStuById(\" " + item.id + "\")'>编辑</button>" +
                "<button class='button' onclick=' deleteStuById(\" " + item.id + "\") '>删除</button> </td>";
            html+="</tr>";
        }
        /*将用户信息显示到页面中的表格中*/
        $("#tb").html(html);
    }


    /*根据id删除一个学生*/
    function deleteStuById(id){
        $.ajax({
            url:"${pageContext.request.contextPath}/student/deleteStu",
            type:"post",
            data: {id:id},
            success:function(info){
                if(info.code == 0){
                    alert("删除成功");
                    LoadUserList();
                }
            }
        });
    }

    /*根据用户id查询用户*/
    function showStuById(id){
        $.ajax({
            url:"${pageContext.request.contextPath}/student/getOneStuById",
            data:{id:id},
            type:'post',
            dataType:'json',
            success:function(info){
                if(info.code == 0){
                    showEditModal(info.student,info.classes);
                }else if(info.code == -1) {
                    showEditModal(null,info.classes);
                }
            },
            erro:function(info){
                alter('网络出现问题');
            }
        });
    }

    /*在模态框中展示一个用户信息*/
    function showEditModal(student,classes) {
        if (student != null) {
            $("#stuIdInput").val(student.id); //传递userId
            $("#nameInput").val(student.name); //编辑用户姓名
            $("#addressInput").val(student.address); //编辑用户地址
            $("#sexSelect").val(student.sex); //根据sex的值来选中select的option
            $("#birthdayInput").val(getLocalTime(new Date(student.birthday)));
            let html = '';
            for(let i = 0 ; i < classes.length ; i++){
                let clazz = classes[i];
                if(clazz.id == student.classes.id){
                    html += "<option value =' " + clazz.id + " ' selected>" + clazz.name + "</option>" ;
                }else {
                    html += "<option value =' " + clazz.id + " ' >" + clazz.name + "</option>" ;
                }
            }
            $("#classSelect").html(html);
            $("#stuIdInput").attr("disabled", "disabled");
        }else{
            //数据归0
            $("#stuIdInput").val(0); //userId
            $("#nameInput").val(""); //用户姓名
            $("#sexSelect").val(""); //根据sex的值来选中select的option
            $("#birthdayInput").val("");
            $("#addressInput").val("");
            $("#classInput").val("");
            let html = '<option>---请选择班级---</option>';
            for(let i = 0 ; i < classes.length ; i++){
                let clazz = classes[i];
                html += "<option value =' " + clazz.id + " ' >" + clazz.name + "</option>" ;
            }
            $("#classSelect").html(html);
        }
        $("#editModal").modal("show");
    }

    /*日期格式转换*/
    function getLocalTime(date) {
        y = date.getFullYear();
        m = ("0" + (date.getMonth() + 1)).slice(-2);
        d = ("0" + date.getDate()).slice(-2);
        return y + "年" + m + "月" + d + "日";
    }

    /*加载所有用户的信息的方法*/
    function LoadUserList(){
        var uid = '${sessionScope.user.id}';
        var role = '${sessionScope.user.role.keyword}'
        var pageSize = $("#pageSizeSelect").children("option:selected").val();
        var currentPage = $("#currentPageSpan").html();

        $.ajax({
            url:"${pageContext.request.contextPath}/sc/getStuSC",
            type:"post",
            dataType:'json',
            data:{
                currentPage:currentPage,
                pageSize:pageSize,
                uid:uid,
                role:role
            },
            success:function(info){
                /*console.log("获取学生信息成功");*/
                /*获取成功后，展示到页面中*/
                showUserList(info.stuList);
                showPage(currentPage,info.totalPage);
            },
            error:function(info){
                console.log(info);
            }
        });
    }

    /*展示当前页数和总页数*/
    function showPage(currentPage,totalPage){
        /*设置总页数，和当前页数*/
        $("#totalPageSpan").html(totalPage);
        $("#currentPageSpan").html(currentPage);
        if(totalPage == '1'){
            $("#nextPageButton").attr("disabled",true);
            $("#prePageButton").attr("disabled",true);
            $("#lastPageButton").attr("disabled",true);
            $("#firstPageButton").attr("disabled",true);
        }else if (currentPage == '1'){
            $("#prePageButton").attr("disabled",true);
            $("#nextPageButton").attr("disabled",false);
            $("#firstPageButton").attr("disabled",true);
            $("#lastPageButton").attr("disabled",false);
        }else if(currentPage == totalPage){
            $("#nextPageButton").attr("disabled",true);
            $("#prePageButton").attr("disabled",false);
            $("#lastPageButton").attr("disabled",true);
            $("#firstPageButton").attr("disabled",false);
        }else {
            $("#nextPageButton").attr("disabled",false);
            $("#prePageButton").attr("disabled",false);
            $("#firstPageButton").attr("disabled",false);
            $("#lastPageButton").attr("disabled",false);
        }
    }

    /*修改模态框中点击确定*/
    function editConfirm(){
        var stuIdValue = $("#stuIdInput").val();
        //console.log(stuIdValue);
        var nameValue = $("#nameInput").val();
        console.log("用户名："+nameValue);
        var addressValue = $("#addressInput").val();
        var sexValue = $("#sexSelect").val();
        var birthdayValue = $("#birthdayInput").val();
        var classValue = $("#classSelect").val();
        console.log("班级id："+classValue);
        var dataValue = {id:stuIdValue, name:nameValue,sex:sexValue,
            birthday:birthdayValue,address:addressValue, class_id:classValue};
        if(stuIdValue == 0){
            if(nameValue != '' && classValue != '' ){
                addUser(dataValue);
            }else {
                console.log("增加学生按钮失效");
                return false;
            }
        }else {
            editUser(dataValue);
        }
    }

    /*增加一个学生*/
    function addUser(dataValue){
        $.ajax({
            url: "${pageContext.request.contextPath}/student/addStu",
            type: 'post', //使用post提交大量数据
            contentType: 'application/x-www-form-urlencoded', //指明是个普通表单提交
            data:dataValue, //传递用户编辑后的信息
            dataType:'json',
            success:function (result) {
                if(result.code == '0'){
                    console.log("添加成功");
                    //再次分页加载数据并显示在页面上
                    $("#editModal").modal("hide");//关闭模态编辑框
                    LoadUserList();
                }else{
                    alert(result.message);
                }
            },
            error:function (err) {
                console.log(JSON.stringify(err));
            }
        });
    }

    //发送修改一个用户的请求
    function editUser(dataValue){
        $.ajax({
            url: "${pageContext.request.contextPath}/student/editStu",
            type: 'post', //使用post提交大量数据
            contentType: 'application/x-www-form-urlencoded', //指明是个普通表单提交
            data:dataValue, //传递用户编辑后的信息
            dataType:'json',
            success:function (result) {
                if(result.code == '0'){
                    //再次分页加载数据并显示在页面上
                    $("#editModal").modal("hide");//关闭模态编辑框
                    LoadUserList();
                }else{
                    alert(result.message);
                }
            },
            error:function (err) {
                console.log(JSON.stringify(err));
            }
        });
    }

    /*根据输入条件查询学生*/
    function searchUesr(index){
        let pageSize = $("#pageSizeSelect").children("option:selected").val();
        let searchInput = $("#searchInput").val();
        let currentPage = index;
        if(searchInput != null && searchInput != ''){
            $.ajax({
                url:"${pageContext.request.contextPath}/student/searchStu",
                type:"post",
                data:{
                    currentPage:currentPage,
                    pageSize:pageSize,
                    keyword:searchInput
                },
                success:function(info){
                    if(info.code == '0'){
                        search = searchInput;
                        showUserList(info.students);
                        showPage(currentPage,info.totalPage);
                    }
                },
                error:function(info){
                    alert("查询失败");
                }
            });
        }else {
            LoadUserList
        }

    }

</script>
</body>


</html>
